package com.clouddot.baipai.ui.fragment.H_MainFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.model.beam.getClassHonorById.getClassHonorByIdResponse;
import com.clouddot.baipai.model.beam.getClassHonorById.honorInfo;
import com.clouddot.baipai.model.beam.getClassInfoById.getClassInfoByIdResponse;
import com.clouddot.baipai.model.beam.getClassInfoList.classInfoItem;
import com.clouddot.baipai.model.beam.getClassInfoList.getClassInfoListResponse;
import com.clouddot.baipai.model.beam.getClassMemberById.getClassMemberByIdResponse;
import com.clouddot.baipai.model.beam.getClassMemberById.studentInfo;
import com.clouddot.baipai.ui.activity.H_SMainActivity;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.adapter.H_Adapter.classMemberRecyclerAdapter;
import com.clouddot.baipai.ui.adapter.H_Adapter.classRecyclerAdapter;
import com.clouddot.baipai.ui.adapter.H_Adapter.classhonorRecyclerAdapter;
import com.clouddot.baipai.ui.dialog.H_Dialog.H_ContentDailog;
import com.clouddot.baipai.ui.util.recycleView.DivierItemLinear;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.SelectedBtnUtil;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPool;
import com.clouddot.baipai.ui.util.ToastUtil;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxy on 2018/4/10.
 */

public class H_ClassFragment extends BaseFragment implements View.OnClickListener {
    private View view;
    private Context context;
    private RecyclerView recyclerView,recyclerView2;
    private classRecyclerAdapter classRecyclerAdapter;
    private classMemberRecyclerAdapter classMemberRecyclerAdapter;
    private classhonorRecyclerAdapter classhonorRecyclerAdapter;
    private List<classInfoItem> list = new ArrayList<classInfoItem>();
    private List<studentInfo> list2 = new ArrayList<studentInfo>();
    private List<honorInfo> list3 = new ArrayList<honorInfo>();
    private ScrollView scrollView ;
//    private TextView tvContent;
    private TextView tv1,tv2,tv3,tv4,tv5;
    private LinearLayout btn1,btn2,btn3,btn4,btn5;
    private TextView name;
    private TextView [] textViews = new TextView[4];
    private LinearLayout[] linearLayouts = new LinearLayout[4];
    private Animation animation;
    private LinearLayout constraintLayout1;
    private ConstraintLayout constraintLayout2;
    private LinearLayout last,next;
    private int pageCount;
    private int CurrentPage = 1;
    private String currentBtn = "notice";
    private Boolean isRunning = false;
    private RelativeLayout relativeLayout;
    private int flag = 1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();

        view = LayoutInflater.from(context).inflate(R.layout.h_f_classfg,null);
    }

    @Override
    protected void initControls() {
        super.initControls();

        tv1 = view.findViewById(R.id.tv1);
        tv2 = view.findViewById(R.id.tv2);
        tv3 = view.findViewById(R.id.tv3);
//        tv4 = view.findViewById(R.id.tv4);
        tv5 = view.findViewById(R.id.tv5);

        btn1 = view.findViewById(R.id.btn1);
        btn2 = view.findViewById(R.id.btn2);
        btn3 = view.findViewById(R.id.btn3);
//        btn4 = view.findViewById(R.id.btn4);
        btn5 = view.findViewById(R.id.btn5);

        textViews[0] = tv1;
        textViews[1] = tv2;
        textViews[2] = tv3;
//        textViews[3] = tv4;
        textViews[3] = tv5;

        linearLayouts[0] = btn1;
        linearLayouts[1] = btn2;
        linearLayouts[2] = btn3;
//        linearLayouts[3] = btn4;
        linearLayouts[3] = btn5;

        linearLayouts[0].setSelected(true);
        textViews[0].setSelected(true);

        animation = AnimationUtils.loadAnimation(context,R.anim.buttom_click_anim);
        animation.setDuration(200);

        name = view.findViewById(R.id.name);

        recyclerView = view.findViewById(R.id.recycle);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(new DivierItemLinear(context,DivierItemLinear.VERTICAL_LIST));
        recyclerView.setItemAnimator(new DefaultItemAnimator());


        recyclerView2 = view.findViewById(R.id.recycle2);
        recyclerView2.setLayoutManager(new GridLayoutManager(context,4));
        recyclerView2.setItemAnimator(new DefaultItemAnimator());

        classRecyclerAdapter = new classRecyclerAdapter(context,list,flag);
        recyclerView.setAdapter(classRecyclerAdapter);

        scrollView = view.findViewById(R.id.scrollView);
//        tvContent = view.findViewById(R.id.tvContent);


        constraintLayout1 = view.findViewById(R.id.left);
        constraintLayout2 = view.findViewById(R.id.right);

        constraintLayout1.startAnimation(animation1);
        constraintLayout2.startAnimation(animation2);

        last = view.findViewById(R.id.last);
        next = view.findViewById(R.id.next);

        relativeLayout = view.findViewById(R.id.loading);
        ImageView loading = view.findViewById(R.id.imgloading);
        loading.startAnimation(loadingAnim);

    }

    @Override
    protected void setListener() {
        super.setListener();
        for(int i = 0 ;i < linearLayouts.length ;i++){
            linearLayouts[i].setOnClickListener(this);
            textViews[i].setOnClickListener(this);
        }
        last.setOnClickListener(lastListener);
        next.setOnClickListener(nextListener);
    }

    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(Env.getAppContext().isInitial) {
            flag = 1;
            relativeLayout.setVisibility(View.VISIBLE);
            currentBtn = "notice";
            runThreadAction(currentBtn);
        }
    }

    @Override
    public void onStop() {
        super.onStop();


    }

    @Override
    public void onClick(View view) {
        H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;


        switch (view.getId()){
            case R.id.btn1:
                flag = 1;
                selectLinear(0);
                break;
            case R.id.btn2:
                selectLinear(1);
                break;
            case R.id.btn3:
                selectLinear(2);
                break;
//            case R.id.btn4:
//                selectLinear(3);
//                break;
            case R.id.btn5:
                flag = 2;
                selectLinear(3);
                break;
            case R.id.tv1:
                flag = 1;
                selectLinear(0);
                break;
            case R.id.tv2:
                selectLinear(1);
                break;
            case R.id.tv3:
                selectLinear(2);
                break;
//            case R.id.tv4:
//                selectLinear(3);
//                break;
            case R.id.tv5:
                flag = 2;
                selectLinear(3);
                break;
        }
    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);
        if(actionName.equals("notice")){
            return Env.getAppPresenter().getClassInfoList(actionName,CurrentPage,Env.getAppContext().itemCount);
        }else if(actionName.equals("honor")){
            return Env.getAppPresenter().getClassHonorByIdList(Env.getAppContext().classId,CurrentPage,Env.getAppContext().itemCount);
        }else if(actionName.matches("[0-9]+")){
            return Env.getAppPresenter().getClassInfoById(actionName);
        }else if(actionName.equals("activity")){
            return Env.getAppPresenter().getClassInfoList(actionName,CurrentPage,Env.getAppContext().itemCount);
        }else if(actionName.equals("classMember")){
            return Env.getAppPresenter().getClassMemberByIdList(Env.getAppContext().classId,CurrentPage,32);
        }
        return null;
    }

    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case  2:
                    TextViews.get(2).setText(sp);
                    break;
            }
        }
    };


    private H_ContentDailog dailog;
    private ImageView close;
    private List<TextView> TextViews;
    private Spanned sp;
    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);

        if(actionName.matches("[0-9]+")) {
            getClassInfoByIdResponse response = (getClassInfoByIdResponse) result;
            if (response.isSuccess()) {
                if (dailog != null) dailog.closeDialog();
                dailog = new H_ContentDailog(context);
                TextViews = dailog.getTextViews();
                TextViews.get(0).setText(response.Title);
                TextViews.get(1).setText("发布时间："+response.CreateTime);
                TextViews.get(2).setText("正在加载...");
                if(response.Detail != null && !response.Detail.isEmpty()) {
                    final String html = EscapeUnescapeUtil.unescape(response.Detail);

                    ThreadPool.getInstance().execute(new Runnable() {
                        @Override
                        public void run() {
                            sp = Html.fromHtml(html, new Html.ImageGetter() {
                                @Override
                                public Drawable getDrawable(String source) {
                                    String s = source.contains("http") ? source : Env.getAppContext().IP + source;
                                    InputStream is = null;
                                    try {
                                        is = (InputStream) new URL(s).getContent();
                                        Drawable d = Drawable.createFromStream(is, null);
                                        d.setBounds(0, 0, d.getIntrinsicWidth(),
                                                d.getIntrinsicHeight());
                                        is.close();
                                        return d;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        return null;
                                    }
                                }
                            }, null);
                            mhandler.sendEmptyMessage(2);
                        }
                    });
                }

                close = dailog.getCloseView();
                close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;

                        dailog.closeDialog();
                    }
                });
                dailog.showDialog();
            } else {
                ToastUtil.showToast(context, response.getErrMsg());
            }
        }else if(actionName.equals("classMember")){
            relativeLayout.setVisibility(View.GONE);

            recyclerView2.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            getClassMemberByIdResponse response = (getClassMemberByIdResponse) result;
            if (response.isSuccess()){
                if(!response.list.isEmpty()){
                    list2 = response.list;
                    pageCount = Integer.parseInt(response.PageCount);
                }else {
                    list2 = new ArrayList<>();
                    studentInfo infoItem = new studentInfo();
                    infoItem.setFullName("当前没有班级成员");
                    infoItem.setSexText("");
                    list2.add(infoItem);
                }
                classMemberRecyclerAdapter = new classMemberRecyclerAdapter(context ,list2);
                recyclerView2.setAdapter(classMemberRecyclerAdapter);
            }else {
                ToastUtil.showToast(context,response.getErrMsg());
                isRunning = true;
                return;
            }
        }else {
            recyclerView.setVisibility(View.VISIBLE);
            recyclerView2.setVisibility(View.GONE);
            relativeLayout.setVisibility(View.GONE);
            if(actionName.equals("notice")){
                getClassInfoListResponse response = (getClassInfoListResponse) result;
                if(response.isSuccess()){
                    if(!response.list.isEmpty()){
                        list = response.list;
                        pageCount = Integer.parseInt(response.PageCount);
                    }else {
                        list = new ArrayList<>();
                        classInfoItem infoItem = new classInfoItem();
                        infoItem.setTitle("当前没有班级通知");
                        infoItem.setCreateTimeText("");
                        list.add(infoItem);

                    }

                    classRecyclerAdapter = new classRecyclerAdapter(context,list,flag);
                    classRecyclerAdapter.setbtnOnclicker(new classRecyclerAdapter.btnOnclicker() {
                        @Override
                        public void onClicked(int position) {
                            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;

                            if (!list.get(position).getTitle().equals("当前没有班级通知")) {
                                runThreadAction(list.get(position).getId());
                            }
                        }
                    });
                    recyclerView.setAdapter(classRecyclerAdapter);
                }else{
                    isRunning = true;
                    ToastUtil.showToast(context,response.getErrMsg());
                    return;
                }
            } else if(actionName.equals("honor")){
                getClassHonorByIdResponse response = (getClassHonorByIdResponse) result;
                if (response.isSuccess()){

                    if(!response.list.isEmpty()){
                        list3 = response.list;
                        pageCount = Integer.parseInt(response.PageCount);
                    }else {
                        list3 = new ArrayList<>();
                        honorInfo infoItem = new honorInfo();
                        infoItem.setHonorItemText("当前没有班级荣誉");
                        infoItem.setEventDate("");
                        infoItem.setHonorLevelText("");
                        list3.add(infoItem);
                    }
                    classhonorRecyclerAdapter = new classhonorRecyclerAdapter(context,list3);
                    recyclerView.setAdapter(classhonorRecyclerAdapter);
                }else {
                    ToastUtil.showToast(context,response.getErrMsg());
                    isRunning = true;
                    return;
                }

            }else if(actionName.equals("activity")){
                getClassInfoListResponse response = (getClassInfoListResponse) result;
                if(response.isSuccess()){
                    if(!response.list.isEmpty()){
                        list = response.list;
                        pageCount = Integer.parseInt(response.PageCount);
                    }else {
                        list = new ArrayList<>();
                        classInfoItem infoItem = new classInfoItem();
                        infoItem.setTitle("当前没有班级活动");
                        infoItem.setCreateTimeText("");
                        list.add(infoItem);

                    }
                    classRecyclerAdapter = new classRecyclerAdapter(context,list,flag);
                    classRecyclerAdapter.setbtnOnclicker(new classRecyclerAdapter.btnOnclicker() {
                        @Override
                        public void onClicked(int position) {
                            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;
                            if (!list.get(position).getTitle().equals("当前没有班级活动")) {
                                runThreadAction(list.get(position).getId());
                            }
                        }
                    });
                    recyclerView.setAdapter(classRecyclerAdapter);
                }else{
                    ToastUtil.showToast(context, response.getErrMsg());
                    isRunning = true;
                    return;
                }
            }
            recyclerView.setVisibility(View.VISIBLE);
        }
        isRunning = true;
    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    private void selectLinear(int i){
        if(isRunning){
            isRunning = false;
            pageCount = 0;
            CurrentPage = 1;
            SelectedBtnUtil.selectedforLinear(linearLayouts,linearLayouts[i]);
            SelectedBtnUtil.selectedforText(textViews,textViews[i]);
            linearLayouts[i].startAnimation(animation);
            textViews[i].startAnimation(animation);
            name.setText(textViews[i].getText());
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            switch (i){
                case 0:
                    currentBtn = "notice";
                    runThreadAction(currentBtn);
                    break;
                case 1:
                    currentBtn = "classMember";
                    runThreadAction(currentBtn);
                    break;
                case 2:
                    currentBtn = "honor";
                    runThreadAction(currentBtn);
                    break;
                case 3:
                    currentBtn = "activity";
                    runThreadAction(currentBtn);
                    break;
            }
        }
    }


    private View.OnClickListener lastListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;


            if (CurrentPage <= 1){
                ToastUtil.showToast(context,"当前是第一页");
                return;
            }
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            CurrentPage--;
            runThreadAction(currentBtn);
        }
    };

    private View.OnClickListener nextListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;
            if (CurrentPage >= pageCount){
                ToastUtil.showToast(context,"当前是最后一页");
                return;
            }
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            CurrentPage++;
            runThreadAction(currentBtn);
        }
    };

    @Override
    public void onPause() {
        super.onPause();
        if(dailog != null) dailog.closeDialog();
    }
}
